Categories
Node.js Tips

Node.js Tips — Test Apps, Retries, and Logging Objects

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

How to Check if a Path is Absolute or Relative

We can check if a path is absolute with the path module’s isAbsolute method.

For instance, we can write:

const path = require('path');
//...

if (path.isAbsolute(somePath)) {
  //...
}

We pass in somePath to the method to check it.

It returns true if it’s an absolute path and false otherwise.

Log JavaScript Objects and Arrays in Winston

We can pretty-print objects with Winston by setting the prettyPrint property.

For instance, we can write:

const level = 'debug';

const logger = new winston.Logger({
  transports: [
    new winston.transports.Console({
      name: 'debug-console',
      level,
      prettyPrint(object) {
        return JSON.stringify(object);
      },
      handleExceptions: true,
      json: false,
      colorize: true
    })
  ],
  exitOnError: false
});

We set the prettyPrint to a function that returns the stringified object to print the object content.

Also, we can log JSON with the %j tag.

For instance, we can write:

logger.log("info", "an object %j", obj);

where obj is an object.

Detecting Test Failures from Within afterEach Hooks in Mocha

We can check the this.currentTest.state property in the afterEach hook to check the status of the test that just runs.

For instance, we can write:

afterEach(function() {
  if (this.currentTest.state === 'failed') {
    // ...
  }
});

If the state is 'failed' , then it failed.

Set a Cookie Value in Node.js

We can set a cookie in the response with the res.cookie method.

For example, we can write:

const cookieParser = require('cookie-parser');
//...

app.use(cookieParser());

app.get('/foo', (req, res) => {
  res.cookie('foo', 'baz');
});

The first argument is the key and the 2nd is the value.

We also include the cookieParser .

Then we can pass in a secret as the argument to sign the cookie.

For instance, we can write:

const cookieParser = require('cookie-parser');
//...

app.use(cookieParser('secret'));

app.get('/foo', (req, res) => {
  res.cookie('foo', 'baz');
});

We pass in a secret key string to sign a cookie.

How to Unit Test Express Router Routes

We can unit test Express router routes by exporting our Express app.

Then we can use Supertest by passing in the exported app to the request function of Supertest.

For instance, if we have the following Express app:

app.js

const app = express();
// ...
const router = require('../app/router')(app);

module.exports = app;

Then we can write our test by writing:

const chai = require('chai');
const should = chai.should();
const sinon = require('sinon');
const request = require('supertest');
const app = require('app');

describe('person route', () => {
  request(app)
    .get('/api/persons')
    .expect('Content-Type', /json/)
    .expect('Content-Length', '4')
    .expect(200, "ok")
    .end((err, res) => {
      if (err) throw err;
    });
});

We pass in the app imported from app.js .

Then we make a GET request by call get .

We use expect to check the response headers and status code.

Then we call end to finish the request and get the response with res in the callback.

Do Repeated Requests Until one Succeeds without Blocking

To make requests repeatedly until it’s successful, we can use the async.retry method.

For instance, we can write:

const async = require('async');
const axios = require('axios');

const makeRequest = async (uri, callback) => {
  try {
    const result = await axios.get(uri);
    callback(null, result);
  } catch (err) {
    callback(err);
  }
};

const uri = 'http://www.test.com/api';

async.retry({
    times: 5,
    interval: 200
  },
  (callback) => {
    return makeRequest(uri, callback)
  },
  (err, result) => {
    if (err) {
      throw err;
    }
  });

We created the makeRequest function that calls the callback with it’s done.

Then we pass that into the async.retry method with the options.

times is the number of times to try.

interval has the retry interval in milliseconds.

The 2nd argument is the async function to call.

The last argument is the callback when the request succeeds or the retries are exhausted.

result has the result. err has the error.

Conclusion

We can use the async.retry method to retry async functions.

We can pretty-print JavaScript objects we log with Winston.

To test an Express app with Supertest, we’ve to export the Express app and use it with Supertest.

Express can set cookies in responses.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *